package com.fang.gateway.config;

import com.fang.common.util.NDBeanUtils;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Random;

/**
 * @Description
 * @Author Bernie_fang
 * @Date 2025/5/17 18:00
 **/
@Configuration
public class OpenFeignConfig {
    @Bean
    public HttpMessageConverters httpMessageConverters() {
        return new HttpMessageConverters();
    }

    @Bean
    public BlockingLoadBalancerClient blockingLoadBalancerClient(
            ReactiveLoadBalancer.Factory<ServiceInstance> loadBalancerClientFactory,
            DiscoveryClient discoveryClient) {
        return new BlockingLoadBalancerClient(loadBalancerClientFactory) {
            @Override
            public <T> ServiceInstance choose(String serviceId, Request<T> request) {
                List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceId);
                if (NDBeanUtils.isObjectEmpty(instanceList)) {
                    return null;
                }
                if (instanceList.size() == 1) {
                    return instanceList.get(0);
                }
                int index = new Random().nextInt(instanceList.size());
                return instanceList.get(index);
            }
        };
    }
}
